package com.xiguthings.xiniu.iot.device.state.controller;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.xiguthings.xiniu.iot.common.DeviceData;
import com.xiguthings.xiniu.iot.common.DeviceDataBody;
import com.xiguthings.xiniu.iot.common.DeviceDataHead;
import com.xiguthings.xiniu.iot.device.state.common.SpringUtils;
import com.xiguthings.xiniu.iot.device.state.handl.EventHandler;
import com.xiguthings.xiniu.iot.device.state.jedis.DeviceDataBuffer;
import com.xiguthings.xiniu.iot.device.state.jedis.JedisClient;

@Component
public class DataCenter {

	private Logger LOGGER = LoggerFactory.getLogger(DataCenter.class);

	private DeviceDataBuffer deviceDataBuffer;
	@Autowired
	@Lazy
	private EventHandler eventHandler;
	@Autowired
	private JedisClient jedisClient;
	// 缓冲区最大的数量
	@Value("${redis.pipeline.buffer.maxSize}")
	private int maxSize;
	// 缓冲区最大缓存时间
	@Value("${redis.pipeline.buffer.maxCacheTime}")
	private long maxCacheTime;

	public DataCenter() {
		init();
		// eventHandler = SpringUtils.getBean(EventHandler.class);
		// jedisClient = SpringUtils.getBean(JedisClient.class);
	}

	private void init() {
		deviceDataBuffer = new DeviceDataBuffer(maxSize, maxCacheTime);
	}

	/**
	 * 获取key
	 * 
	 * @param deviceData
	 * @return
	 */
	public static String getDeviceStatusRedisKey(DeviceData deviceData) {
		String hkey = deviceData.getHead().getDeviceId() + "";
		return hkey;
	}

	/**
	 * 查询历史中的proxyid
	 * 
	 * @param deviceData
	 * @return proxyId
	 */
	public String queryOldProxyId(DeviceData deviceData) {
		if (deviceData == null || deviceData.getHead() == null) {
			return null;
		}
		// 先查询buffer中是否有
		DeviceData oldDeviceData = deviceDataBuffer.getOldDeviceData(deviceData);
		if (oldDeviceData != null) {
			return oldDeviceData.getHead().getProxyId();
		}
		// 在查询redis中有没有
		String hkey = DataCenter.getDeviceStatusRedisKey(deviceData);
		String tsAndProxyId = jedisClient.hget(hkey, "_proxy_id");
		if (StringUtils.isBlank(tsAndProxyId)) {
			return null;
		}

		String[] strings = tsAndProxyId.split(",");
		return strings[1];

	}

	/**
	 * 接收需要处理的消息
	 *
	 * @param dataStr
	 */
	public void receiveMessage(String dataStr) {
		try {
			LOGGER.debug("收到的消息：\n{}", dataStr);
			DeviceData deviceData = formatMessage(dataStr);
			// 处理proxy变更事件
			if (eventHandler == null) {
				ApplicationContext applicationContext = SpringUtils.getApplicationContext();
				while (applicationContext == null) {
					Thread.sleep(1000);
					applicationContext = SpringUtils.getApplicationContext();
				}
				eventHandler = SpringUtils.getBean(EventHandler.class);
			}
			eventHandler.handleProxyChange(deviceData);
			// 存入buffer
			deviceDataBuffer.add(deviceData);
		} catch (Exception e) {
			LOGGER.error("", e);
		}
	}

	/**
	 * + 将收到的字符串，转成java对象
	 *
	 * @param dataStr
	 * @return
	 */
	private DeviceData formatMessage(String dataStr) {
		try {
			String[] partArr = dataStr.split("\\|\\|");
			DeviceData deviceData = new DeviceData();
			deviceData.setHead(JSON.parseObject(partArr[0], DeviceDataHead.class));
			deviceData.setBody(JSON.parseObject(partArr[1], DeviceDataBody.class));
			return deviceData;
		} catch (Exception e) {
			LOGGER.error("接收到kafka的数据格式不正确。收到的是消息:{}", dataStr);
		}
		return null;
	}
}
